package jp.sourceforge.akjrcp.youtubedl;


import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.commons.ui.FileDirChoicer;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeEvent;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeListener;
import jp.sourceforge.akjrcp.flvtools.basic.FLVToolsPage;
import jp.sourceforge.akjrcp.ui.DirectoryPathCombo;
import jp.sourceforge.akjrcp.ui.EditableListData;
import jp.sourceforge.akjrcp.ui.FileOverwriteControler;
import jp.sourceforge.akjrcp.ui.ProgressAndQuee;
import jp.sourceforge.akjrcp.ui.SimpleEditableListData;
import jp.sourceforge.akjrcp.ui.URLBasedExecuterListener;
import jp.sourceforge.akjrcp.util.ClipboardUtil;
import jp.sourceforge.akjrcp.util.ProgressMonitorUtils;
import jp.sourceforge.akjrcp.util.YoutubeDLExecuter;
import jp.sourceforge.akjrcp.util.YoutubeDLUtils;
import jp.sourceforge.akjrcp.util.YoutubeUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.part.ViewPart;


public class YoutubeDLView extends ViewPart{
	public static Log log=LogFactory.getLog(YoutubeDLView.class);
	
	public static final String ID = YoutubeDLView.class.getName();

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	
	Composite composite;

	

	public void setUrl(String url){
		if(YoutubeUtils.isYoutubeVideoURL(url)){
		urlLine.setText(url);
		}
	}
	//private YoutubeDLExecuteControler youtubeDLExecuteControler;
	
	Text urlLine;
	//i have no idea,i know this is horrible storategy.//maybe added from some where.
	public static List<YoutubeDLListener> youtubeDLListeners=new ArrayList<YoutubeDLListener>();
	
	private int sleeptime=3;//for stop blocking.
	private boolean downloading;//check it
	private EditableListData currentData;
	
	private String userText;
	private String passwordText;
	private Button execButton;
	private boolean cancelling;
	public void createPartControl(Composite root) {
	CTabFolder tab=new CTabFolder(root,SWT.NULL);
	CTabItem tabItem1 = new CTabItem(tab, SWT.NONE);
	
	tabItem1.setText(Messages.getString("youtubedl.main"));
	Composite parent=new Composite(tab,SWT.NULL);
	tabItem1.setControl(parent);
	tab.setSelection(0);
	//tab.showItem(tabItem1);
		
		
		parent.setLayout(new GridLayout(1,false));
		
		Composite split2=new Composite(parent,SWT.NULL);
		split2.setLayout(new GridLayout(2,false));
		

		//rename and download
		Composite renameAndExec=new Composite(split2,SWT.NULL);
		renameAndExec.setLayout(new GridLayout(1,false));
		
		renameFile = new Button(renameAndExec,SWT.CHECK);
		renameFile.setText(Messages.getString("youtubedl.rename_file"));
		renameFile.setToolTipText(Messages.getString("youtubedl.rename_file_tooltip"));
		renameFile.setSelection(PlatformUI.getPreferenceStore().getBoolean(YoutubeDLUtils.RENAME_FILE));
		renameFile.addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				storeValue(e.getSource());
				rename=renameFile.getSelection();
			}
			
		});
		
		Group compo2=new Group(split2,SWT.NULL);
		compo2.setLayout(new GridLayout(1,false));
		compo2.setText(Messages.getString("youtubedl.group_download"));
		
		
		
		
		pathCombo = new DirectoryPathCombo(compo2,SWT.NULL,Akj_betasPlugin.getDefault().getPreferenceStore(),FLVToolsPage.EXPLORER_PATHS,jp.sourceforge.akjrcp.util.image.ImageUtils.loadImage(Akj_betasPlugin.PLUGIN_ID, "icons/opendir.gif"),jp.sourceforge.akjrcp.util.image.ImageUtils.loadImage(Akj_betasPlugin.PLUGIN_ID, "icons/showin.gif"));
	
		
		
		
		Composite dlGroup=new Composite(parent,SWT.NULL);
		dlGroup.setLayout(new GridLayout(2,false));
		
		
		execButton=new Button(dlGroup,SWT.NULL);
		execButton.addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				addURL(urlLine.getText());
				urlLine.setText("");
			}});
		execButton.setText(Messages.getString("youtubedl.exec"));
		
		Group compo=new Group(dlGroup,SWT.NULL);
		//compo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		compo.setText(Messages.getString("youtubedl.group_url"));
		compo.setLayout(new GridLayout(2,false));
		Button pasteButton=new Button(compo,SWT.NULL);
		pasteButton.setImage(jp.sourceforge.akjrcp.util.image.ImageUtils.loadImage(Akj_betasPlugin.PLUGIN_ID, "icons/url_clipboard.gif"));
		pasteButton.setAlignment(SWT.CENTER);
		pasteButton.addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				pasteAction();
			}
			
		});
		
		
		
		GridData labelData=new GridData();
		labelData.minimumWidth=32;
		labelData.minimumHeight=32;
		labelData.grabExcessHorizontalSpace=true;
		labelData.grabExcessVerticalSpace=true;
		pasteButton.setLayoutData(labelData);
		pasteButton.setToolTipText(Messages.getString("youtubedl.paste_clipboard"));
		
		GridData urlData=new GridData();
		urlData.minimumWidth=500;
		urlData.minimumHeight=24;
		urlData.grabExcessHorizontalSpace=true;
		urlData.grabExcessVerticalSpace=false;
		
		
		urlLine=new Text(compo,SWT.NULL);
		urlLine.setFont(new Font(null,"MS-Mincho",12,SWT.NONE));
		urlLine.setLayoutData(urlData);
		
		urlLine.addModifyListener(new ModifyListener(){

			public void modifyText(ModifyEvent e) {
			
				execButton.setEnabled(YoutubeUtils.isYoutubeVideoURL(urlLine.getText()));
			}
			
		});
		
		
		/*
		urlLine.addKeyListener(new KeyListener(){

			public void keyPressed(KeyEvent e) {
				
			}

			public void keyReleased(KeyEvent e) {
				youtubeDLExecuteControler.updateControlSwitch();
			}
			
		});*/
		pathCombo.updatePaths();
		
	
		
		
		
		
		
		
		
		

		
		
		if(!isYoutubeDLExist()){
			Akj_betasPlugin.getDefault().getProcessPrinter().printError(Messages.getString("youtubedl.error_no_youtubedl")+"\n");
		}
		
		
		try{
			pasteAction();
	
		}catch(Exception e){
			log.warn("paste faild");
		}
		
		Group compo3=new Group(parent,SWT.NULL);
		compo3.setLayout(new GridLayout(4,true));
		Label userLabel=new Label(compo3,SWT.NULL);
		userLabel.setText(Messages.getString("youtubedl.userID"));
		user = new Text(compo3,SWT.NULL);
		user.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		Label passwordLabel=new Label(compo3,SWT.NULL);
		passwordLabel.setText(Messages.getString("youtubedl.password"));
		password = new Text(compo3,SWT.PASSWORD);
		password.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		user.setText(Akj_betasPlugin.getDefault().getPreferenceStore().getString(YoutubeDLSettingPage.USER));
		
		String passwordText=decrypteValue(KEY,Akj_betasPlugin.getDefault().getPreferenceStore().getString(YoutubeDLSettingPage.PASSWORD));
		if(passwordText!=null){
			password.setText(passwordText);
		}
		
		getSite().getPage().addPartListener(new IPartListener2(){

			public void partActivated(IWorkbenchPartReference partRef) {
				// TODO Auto-generated method stub
				
			}

			public void partBroughtToTop(IWorkbenchPartReference partRef) {
				// TODO Auto-generated method stub
				
			}

			public void partClosed(IWorkbenchPartReference partRef) {
				
			}

			public void partDeactivated(IWorkbenchPartReference partRef) {
				log.trace("deactivate");
				if(!user.isDisposed()){
					Akj_betasPlugin.getDefault().getPreferenceStore().setValue(YoutubeDLSettingPage.USER, user.getText());
					//
					
					try {
						if(password.getText().length()==0){
							 Akj_betasPlugin.getDefault().getPreferenceStore().setValue(YoutubeDLSettingPage.PASSWORD, "");
						}else{
							String passwordValue=encryptValue(KEY,password.getText());
				            Akj_betasPlugin.getDefault().getPreferenceStore().setValue(YoutubeDLSettingPage.PASSWORD, passwordValue);
				           
						}
				            
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		           
				}
			}

			public void partHidden(IWorkbenchPartReference partRef) {
				// TODO Auto-generated method stub
				
			}

			public void partInputChanged(IWorkbenchPartReference partRef) {
				// TODO Auto-generated method stub
				
			}

			public void partOpened(IWorkbenchPartReference partRef) {
				// TODO Auto-generated method stub
				
			}

			public void partVisible(IWorkbenchPartReference partRef) {
				// TODO Auto-generated method stub
				
			}});
		
		
		CTabItem tabItem2 = new CTabItem(tab, SWT.NONE);
		
		tabItem2.setText(Messages.getString("youtubedl.download"));
		
		
		progressAndQuee = new ProgressAndQuee(tab,SWT.NULL);
		tabItem2.setControl(progressAndQuee);
		progressAndQuee.getCancelAllButton().addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				cancelling=true;
				progressAndQuee.getEditableList().removeAll();//delete all ques.
				if(youtubeExecuter!=null){
					youtubeExecuter.cancel();//cancel current
				}
				
			}});
		
		progressAndQuee.getCancelButton().addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				if(youtubeExecuter!=null){
					youtubeExecuter.cancel();//cancel current
				}
			}});
		progressAndQuee.getCancelButton().setEnabled(false);
		progressAndQuee.getCancelAllButton().setEnabled(false);
	}
	
	public void addURL(String url){
		if(isAlreadyDownloading(url)){
			log.info("already download:"+url);
			return;
		}
		try {
			SimpleEditableListData data=new SimpleEditableListData();
			String label;
			
			if(!password.getText().equals("")&&!password.getText().equals("")){
				//label=YoutubeUtils.getTitle(YoutubeUtils.getId(new URL(url)),user.getText(),password.getText());
				label=YoutubeUtils.getTitle(new URL(url));
				//log.infolabel:"+label);
				if(label.equals("Broadcast Yourself")){
					label=YoutubeUtils.getId(new URL(url));
				}
			}else{
				label=YoutubeUtils.getTitle(new URL(url));
			}
			
			data.setLabel(label);
			data.setValue(url);
			log.warn("addData:"+data.getLabel()+","+data.getValue());
			progressAndQuee.addData(data);
			log.warn("dataSize:"+progressAndQuee.getEditableList().countDatas());
			if(!downloading){
				startDownload();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void startDownload(){
		cancelling=false;
		new StartDownload().start();
	}
	
	
	public class POPData extends Thread{
		public void run(){
			currentData=progressAndQuee.getEditableList().popData();
		}
	}
	private YoutubeDLExecuter youtubeExecuter;
	
	public class BeforeExecute extends Thread{
		public void run(){
			
			progressAndQuee.getCancelAllButton().setEnabled(true);
			progressAndQuee.getCancelButton().setEnabled(true);
			exportDir=pathCombo.getSelectedDirectory();
			progressAndQuee.setHeaderLabelText(currentData.getLabel());
			progressMonitor=ProgressMonitorUtils.getProgressMonitor();
			userText=user.getText();
			passwordText=password.getText();
		}
	}
	
	public class AfterExecute extends Thread{
		public void run(){
			progressAndQuee.getCancelAllButton().setEnabled(false);
			progressAndQuee.getCancelButton().setEnabled(false);
			progressAndQuee.setHeaderLabelText("");
			progressAndQuee.getProgressBar().setSelection(0);
		}
	}
	
	public class StartDownload extends Thread{
		

		public void run(){
			downloading=true;
			log.info("StartDownload:"+progressAndQuee.getEditableList().countDatas());
			while(progressAndQuee.getEditableList().countDatas()>0){
				if(cancelling){
					log.warn("cancell all");
					break;
				}
				log.info("datas:"+progressAndQuee.getEditableList().countDatas());
				//pop
				getSite().getShell().getDisplay().syncExec(new POPData());
				
				if(currentData!=null){
				getSite().getShell().getDisplay().syncExec(new BeforeExecute());
				log.info(currentData);
				//download
				youtubeExecuter = new YoutubeDLExecuter();
				youtubeExecuter.setExportDir(exportDir.getAbsolutePath());
				youtubeExecuter.setBestQuarity(PlatformUI.getPreferenceStore().getBoolean(YoutubeDLUtils.YOUTUBE_DL_BEST_QUARITY));
				String python=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_PYTHON);
				String dl_py=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_YOUTUBE_DL_PY);
				String dl_exe=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_YOUTUBE_DL_EXE);
				boolean setPath=false;
				if(python.length()>0 && new File(python).exists()){
					if(dl_py.length()>0 && new File(dl_py).exists()){
						youtubeExecuter.setPythonPath(python);
						youtubeExecuter.setYoutubeDLPath(dl_py);
						setPath= true;
					}
				}
				if(!setPath){
					if(dl_exe.length()>0 && new File(dl_exe).exists()){
						youtubeExecuter.setYoutubeDLPath(dl_exe);
						setPath= true;
					}else{
						log.warn("youtube-dl not found");
					}
				}
				
				if(!userText.equals("")){
				youtubeExecuter.setUser(userText);
				}
				if(!passwordText.equals("")){
				youtubeExecuter.setPassword(passwordText);
				}
				
				youtubeExecuter.setRenameFile(rename);
				youtubeExecuter.setExecuteListener(new DLMonitor());
				try {
					youtubeExecuter.execute(new URL[]{new URL((String)currentData.getValue())});
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
				currentData=null;
				if(progressAndQuee.getEditableList().countDatas()>0){
					//stop conninue download
					try {
						log.warn("wait download:"+sleeptime);
						Thread.sleep(sleeptime*1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			getSite().getShell().getDisplay().syncExec(new AfterExecute());
			downloading=false;
			
	}
	}
	
	public boolean isAlreadyDownloading(String url){
		if(currentData!=null){
			if(currentData.getValue().equals(url)){
				return true;
			}
		}
		EditableListData[] datas=progressAndQuee.getEditableList().getDatas();
		for (int i = 0; i < datas.length; i++) {
			if(datas[i].getValue().equals(url)){
			return true;	
			}
		}
		return false;
	}
	
	public static String KEY="teaspi12-59";
	public static String encryptValue(String key,String value){
		try{
			String ret="";
		 javax.crypto.spec.SecretKeySpec sksSpec = 
		        new javax.crypto.spec.SecretKeySpec(key.getBytes(), "Blowfish");
		    javax.crypto.Cipher cipher = 
		        javax.crypto.Cipher.getInstance("Blowfish");
		    cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, sksSpec);
		    byte[] encrypted = cipher.doFinal(value.getBytes());
		    for (int i = 0; i < encrypted.length; i++) {
				ret+=encrypted[i];
				if(i!=encrypted.length-1){
					ret+=",";
				}
			}
		    return ret;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	public static String decrypteValue(String key,String value){
		try{
		String tmps[]=value.split(",");
		if(tmps.length==0){
			return null;
		}
		if(tmps[0].equals("")){
			return null;
		}
		
		byte encrypted[]=new byte[tmps.length];
		for(int i=0;i<tmps.length;i++){
			
			encrypted[i]=Byte.parseByte(tmps[i]);
		}
		
		javax.crypto.spec.SecretKeySpec sksSpec = 
	        new javax.crypto.spec.SecretKeySpec(key.getBytes(), "Blowfish");
	    javax.crypto.Cipher cipher = 
	        javax.crypto.Cipher.getInstance("Blowfish");
	    cipher.init(javax.crypto.Cipher.DECRYPT_MODE, sksSpec);
	    byte[] decrypted = cipher.doFinal(encrypted);
	    return new String(decrypted);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
	}
	public void pasteAction(){
		//filter url
		String text=ClipboardUtil.getCurrentText(PlatformUI.getWorkbench().getDisplay());
		if(text!=null){
			String[] lines=text.split("\n");
			if(YoutubeUtils.isYoutubeVideoURL(lines[0])){
			urlLine.setText(lines[0]);
			}
		}
	}
	


	public void storeValue(Object object){
		if(object==renameFile){
			PlatformUI.getPreferenceStore().setValue(YoutubeDLUtils.RENAME_FILE, renameFile.getSelection());
		}
	}
	
	public boolean isYoutubeDLExist(){
		
	String python=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_PYTHON);
	String dl_py=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_YOUTUBE_DL_PY);
	String dl_exe=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_YOUTUBE_DL_EXE);
	if(python.length()>0 && new File(python).exists()){
		if(dl_py.length()>0 && new File(dl_py).exists()){
			return true;
		}
	}
	
	if(dl_exe.length()>0 && new File(dl_exe).exists()){
		return true;
	}
	
	return false;
	}
	
	public class OverwriteCheck implements FileStatusChangeListener{

		public void addList(FileStatusChangeEvent event) {
			File f=new File(event.getFilePath());
			if(f.exists()){
				FileOverwriteControler controler=new FileOverwriteControler(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),FileOverwriteControler.MODE_YES_NO_CANCEL);
				boolean r=controler.canOverwrite(f);
				if(r==false){
					((FileDirChoicer)event.getSource()).removePath();//cancel
				}
			}
		}

		public void removeList(FileStatusChangeEvent event) {
			
		}
		
	}
	

	

	private File exportDir;
	private DirectoryPathCombo pathCombo;
	
	
	private IProgressMonitor progressMonitor;

	private Button renameFile;
	private boolean rename;

	private Text user;

	private Text password;

	private ProgressAndQuee progressAndQuee;
	/*
	public class YoutubeDLExecuteControler extends ExecutingControler{

		

		private String userText;
		private String passwordText;

		private YoutubeDLExecuter youtubeExecuter;


		
		public void afterExecute() {
			
		}

		public void beforeExecute() {
			urlText=urlLine.getText();
			exportDir=pathCombo.getSelectedDirectory();
			progressMonitor=ProgressMonitorUtils.getProgressMonitor();
			rename=renameFile.getSelection();
			
			if(!user.getText().equals("")){
				userText=user.getText();
			}
			
			if(!password.getText().equals("")){
				passwordText=password.getText();
			}
		}

		public boolean canExecute() {
			if(isYoutubeDLExist() && pathCombo.getSelectedDirectory()!=null && YoutubeUtils.isYoutubeVideoURL(urlLine.getText())){
				return true;
			}
			return false;
		}

		public void cancelExecuting() {
			if(youtubeExecuter!=null){
			youtubeExecuter.cancel();
			}
		}


		public void inExecute(){
			youtubeExecuter = new YoutubeDLExecuter();
			youtubeExecuter.setExportDir(exportDir.getAbsolutePath());
			
			String python=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_PYTHON);
			String dl_py=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_YOUTUBE_DL_PY);
			String dl_exe=PlatformUI.getPreferenceStore().getString(YoutubeDLUtils.PATH_YOUTUBE_DL_EXE);
			boolean setPath=false;
			if(python.length()>0 && new File(python).exists()){
				if(dl_py.length()>0 && new File(dl_py).exists()){
					youtubeExecuter.setPythonPath(python);
					youtubeExecuter.setYoutubeDLPath(dl_py);
					setPath= true;
				}
			}
			if(!setPath){
				if(dl_exe.length()>0 && new File(dl_exe).exists()){
					youtubeExecuter.setYoutubeDLPath(dl_exe);
					setPath= true;
				}else{
					log.warn("youtube-dl not found");
				}
			}
			
			youtubeExecuter.setUser(userText);
			youtubeExecuter.setPassword(passwordText);
			
			youtubeExecuter.setRenameFile(rename);
			youtubeExecuter.setExecuteListener(new DLMonitor());
			try {
				youtubeExecuter.execute(new URL[]{new URL(urlText)});
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	*/
	public class UpdateExplorer extends Thread{
		public void run(){
			
			for (int i = 0; i < youtubeDLListeners.size(); i++) {
				youtubeDLListeners.get(i).downloaded("");
			}
			/*
			IWorkbenchPage page=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
			//log.info(page.findViewReference(ExplorerView.ID)); maybe null
			
			IPerspectiveDescriptor[] decs=page.getOpenPerspectives();
			for (int i = 0; i < decs.length; i++) {
				
			}
			//IViewDescriptor decriptor=PlatformUI.getWorkbench().getViewRegistry().find(ExplorerView.ID);
			
			IWorkbenchPage pages[]=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPages();
			for (int i = 0; i < pages.length; i++) {
				log.info(i+""+pages[i].getLabel());
			}
			IViewReference[] references=page.getViewReferences();
			for (int i = 0; i < references.length; i++) {
				log.info(references[i].getPartName()+","+references[i].getId());
				
				ExplorerView view=(ExplorerView)windows[i].getActivePage().findView(ExplorerView.ID);
				if(view!=null){
					view.reload();
					return;
				}
			}
		log.info("explorer is null");
			*/
			
			
		
		}
	}
	
	public class ProgressWorked extends Thread{
		private int value;
		public ProgressWorked(int value){
			this.value=value;
		}
		public void run(){
			progressAndQuee.getProgressBar().setSelection(value);
		}
	}
	
	public class DLMonitor implements URLBasedExecuterListener{
		int lastprocess=0;
		public void afterConvert() {
			
		}

		public void beforeConvert() {
			
		}

		public void endConvert(URL url) {//TODO add file
			ProgressMonitorUtils.doneMonitor(progressMonitor, true);
			//update explorer view
			PlatformUI.getWorkbench().getDisplay().syncExec(new UpdateExplorer());
		}

		public void faildConvert(URL url, String message) {
			ProgressMonitorUtils.doneMonitor(progressMonitor, true);
			setStatusValue(Messages.getString("youtubedl.faild"));
			Akj_betasPlugin.getDefault().getProcessPrinter().printError(Messages.getString("youtubedl.faild.detail")+"\n");
		}

		public void printProcess(String line) {
			if(YoutubeDLExecuter.isProgressLine(line)){
				int value=YoutubeDLExecuter.getProgressPersent(line);
				int add=value-lastprocess;
				if(add>0){
					ProgressMonitorUtils.workedMonitor(progressMonitor, add, true);
					PlatformUI.getWorkbench().getDisplay().asyncExec(new ProgressWorked(value));
				}
				lastprocess=value;
			}else{
				Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(line);
			}
		}

		public void startConvert(URL url) {
			ProgressMonitorUtils.beginMonitor(progressMonitor, "Download:"+url.toString(), 100, true);
			lastprocess=0;
		}
		
	}
	
	
	public void setStatusValue(String value){
		PlatformUI.getWorkbench().getDisplay().asyncExec(new SetMessage(value));
		
	}
	
	public class SetMessage implements Runnable{
		String message;
		SetMessage(String message){
			this.message=message;
		}
		public void run(){
			WorkbenchWindow workbenchWindow =  (WorkbenchWindow) getViewSite().getWorkbenchWindow();
			IActionBars actionBars = workbenchWindow.getActionBars();
			IStatusLineManager manager = actionBars.getStatusLineManager();
			manager.setMessage(message);
		}
	}
	
	


	
	public void setFocus() {
		urlLine.setFocus();
	}
	
}